/**
 * 说明：通用下拉层位置定位，当下拉空间不够，向上展开
 * 调用方法
 * import popup from '@/utils/popup'
 * 示例:
 * this.$nextTick(()=> {
 * 		popup.create({drop:this.$refs.drop})
 * })
 * 
 * this.$nextTick(()=> {
 * 	popup.position({
 * 		trigger:this.$refs.trigger,//触发层\
 * 	 	drop:this.$refs.drop,//下拉层
 * 	  	body:false,//是否将弹层置于body中
 *   })
 * })
 * 
 */
let popup = {
	create:function(el) {	//创建弹层
		// console.log('创建弹层',el)
		const body = document.querySelector("body");
		if (body.append) {
			body.append(el.drop);
		} else {
			body.appendChild(el.drop);
		}
	},
  delete:function(el) {
    const body = document.querySelector("body");
    if(el.drop) {
      body.removeChild(el.drop)
    }
  },
	position:function(el) {	//弹层定位
        if(el.drop) {
            // 位置定位
            const DOMRect1 = el.trigger.getBoundingClientRect(),
                  DOMRect2 = el.drop.getBoundingClientRect();
            const _l1 = DOMRect1.left,
                  _l2 = DOMRect2.left,
                  _t1 = DOMRect1.top,
                  _w1 = DOMRect1.width,
                  _w2 = DOMRect2.width,
                  _h1 = DOMRect1.height,
                  _h2 = el.drop.offsetHeight, //下拉层高度,这个算出来准
                  _t2 = DOMRect2.top,
                  _st = window.pageYOffset, //滚动高度
                  _ch = document.documentElement.clientHeight, //浏览器可视化窗口的大小  
                  _ww = window.innerWidth; //浏览器内宽

            // 处理下拉层宽度太大，超出右侧屏幕。当超出时，右侧对齐边缘
            if(_ww < (_w2 + _l2)) {
              el.drop.style.marginLeft = -(_w2+_l2-_ww+17)+'px';
            }

            // 处理下拉层位置
            if(el.body){
              if (Number(_t1+_h1+_h2) > _ch) {
                el.drop.setAttribute('position', 'top');
                el.drop.style.top = (_t1-_h2+_st)+'px';
                el.drop.style.left = _l1+'px';
                el.drop.style.transformOrigin = 'center bottom';
              }else{
                el.drop.removeAttribute("position");
                el.drop.style.top = (_t1+_h1+_st)+'px';
                el.drop.style.left = _l1+'px';
              }
            }else{
              if (Number(_t1+_h1+_h2) > _ch) {
                el.drop.setAttribute('position', 'top');
                el.drop.style.marginTop = '-'+Number(_h1+_h2)+'px';
                el.drop.style.transformOrigin = 'center bottom';
              }else{
                el.drop.removeAttribute("position");
                el.drop.style.marginTop = '';
              }
            }
        }
	},
}
export default popup